package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    /*注入FreeMarkerConfigurer对象*/
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录


    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {

        setmealDao.add(setmeal);

        if (checkgroupIds != null && checkgroupIds.length > 0) {
            //绑定套餐和检查组的多对多关系
            setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        }

        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());

        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    private void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }
    //生成套餐详情静态页面（多个）
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {

        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal",setmealDao.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",dataMap);
        }
    }
    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        //存放静态页面所需数据
        Map<String, Object> dataMap = new HashMap<>();
        //名称要和静态页面使用名称一致
        dataMap.put("setmealList", setmealList);
        //传入参数为页面模板名称，生成的页面名称和页面所需数据
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);

    }

    //通用的方法，用于生成静态页面
    public void generateHtml(String templateName,String htmlPageName,Map<String, Object> dataMap){
        //获取freemarker的配置对象，已经交由spring管理，并且设置了模板文件存放目录和字符集
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            //根据传入的模板文件名加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成数据
            File docFile = new File(outPutPath+"/"+htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile),"UTF-8"));

            //输出文件
            template.process(dataMap,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        int currentPage = queryPageBean.getCurrentPage();
        int pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);

        Page<Setmeal> page = setmealDao.findByCondition(queryString);

        Long total = page.getTotal();
        List rows = page.getResult();


        return new PageResult(total,rows);
    }

    //根据id查询套餐信息，包括套餐组和套餐项
    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    //根据检查套餐id查询关联的检查组
    @Override
    public List<Integer> findCheckgroupIdsBySetmealId(Integer setmealId) {
        return setmealDao.findCheckgroupIdsBySetmealId(setmealId);
    }

    //编辑套餐
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //保存编辑信息
        setmealDao.edit(setmeal);
        //删除旧关系
        setmealDao.deleteAssoication(setmeal.getId());
        //建立新关系
        setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);

        //编辑套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    //根据id删除套餐
    @Override
    public void deleteById(Integer id) {
        //检查删除id是否和检查组有关联
        List<Integer> list =  setmealDao.findCheckgroupIdsBySetmealId(id);

        if (!list.isEmpty()) {
            throw new RuntimeException();
        }else {
            setmealDao.deleteById(id);
        }

        //删除套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    //获取所有套餐信息
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    @Override
    public Integer findnameById(String name) {
        return setmealDao.findnameById(name);
    }

    @Override
    public Integer findSetmealMoney(Integer id) {
        return setmealDao.findSetmealMoney(id);
    }

    @Override
    public Double findSetmealNum(Integer id, ArrayList<String> dayList) {
        Double n = 0.0;
        for (String s : dayList) {
            //每天已到诊的预约套餐数量
            Integer num=setmealDao.findSetmealNum(id,s);
            n += num;
        }
        return n;
    }

    @Override
    public List<String> findSetmealNameCount() {
        return setmealDao.findSetmealNameCount();
    }

    //将图片名称保存到Redis
    private void savePic2Redis(String pic) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
    }

    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {

        for (Integer checkgroupId : checkgroupIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("setmeal_id", id);
            map.put("checkgroup_id", checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }
}
